<?php

namespace App\Web\Controller;

use App\Facades\Captcha;
use App\Service\ExternalAPI\CaseResumeApi;
use App\Service\ImgCaptcha;
use App\Web\Facades\UserAuth;
use App\Web\Model\Login as LoginModel;
use App\Web\Model\Redis\LoginSession;
use App\Web\Model\User as UserModel;
use EchoPHP\Http\Request;
use App\Web\Model\Operator as OprModel;
use PhpOffice\PhpSpreadsheet\Reader\Xls\MD5;

Class Operator extends Controller {

    /**
     * 获取当前用户信息
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function getinfo(Request $request) {
        $oprId = $request->getParam('userid', 0) ?: $this->getLoginId();
        $userModel = new UserModel();
        $oprInfo = $userModel->getInfoWithTeam($oprId);
        return $this->json([
            'status' => !empty($oprInfo),
            'message' => empty($oprInfo) ? '用户信息查询失败' : '查询成功',
            'oprinfo' => $oprInfo
        ]);
    }

    /**
     * 编辑并保存当前用户信息
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    /*public function editinfo(Request $request) {
        $params = [
            'email' => $request->getPost('email'),
            'mobilephone' => $request->getPost('mobilephone'),
            'cname' => $request->getPost('cname'),
            'position' => $request->getPost('position'),
            'department' => $request->getPost('department'),
        ];

        $loginId = $this->getLoginId();
        $oprModel = new OprModel();
        $result = $oprModel->editInfo($loginId, $params);

        return $this->json($result);
    }*/

    /**
     * 修改密码
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function resetPwd(Request $request) {
        $params = [
            'userid' => $this->getLoginId(),
            'oldpwd' => $request->getPost('oldpwd'),
            'newpwd' => $request->getPost('newpwd'),
            'newpwd_confirm' => $request->getPost('newpwd_confirm'),
        ];

        $oprId = $this->getLoginId();
        $oprModel = new OprModel();
        $result = $oprModel->resetPwd($oprId, $params);

        return $this->json($result);
    }

    /**
     * 刷新登录认证token
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function refreshAuthToken(Request $request) {
        $loginId = $this->getLoginId();
        $loginSession = new LoginSession();
        $authToken = $loginSession->refreshAuthToken($loginId);
        return $this->json([
            'status' => $authToken === false ? false : true,
            'msg' => $authToken === false ? '刷新失败' : '刷新成功',
            'authToken' => $authToken,
        ]);
    }

    /**个人首页报表数据
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function getReportInfo(Request $request) {
        $oprId = $this->getLoginId();
        $date = date('Y-m-d', strtotime($request->getParam('date', '')));
        $oprModel = new OprModel();
        $reportList = $oprModel->getReportInfo($oprId, $date);

        return $this->json(['status' => true, 'message' => '获取成功', 'reportlist' => $reportList]);
    }

    /**今日任务 获取全部任务
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function getTodayTask() {
        $oprId = $this->getLoginId();
        $oprModel = new OprModel();
        $taskList = $oprModel->getTodayTask($oprId);

        return $this->json(['status' => true, 'message' => '获取成功', 'taskList' => $taskList]);
    }

    /**个人首页日历任务，前后三个月
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function getMonthTasks(Request $request) {
        $oprId = $this->getLoginId();
        $date = $request->getParam('date/s');//任务日期，标准时间格式，定位到年月
        //$date = '2019-8';
        $oprModel = new OprModel();
        $taskList = $oprModel->getMonthTasks($oprId, $date);

        return $this->json(['status' => true, 'message' => '获取成功', 'tasklist' => $taskList['tasklist'], 'waitcount' => $taskList['waitcount']]);
    }

    /**待跟进人员信息列表
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function getWaitList(Request $request) {
        $pageNum = $request->getParam('pagenum/d', 1);
        $pageLimit = $request->getParam('pageLimit/d', 10);
        $dateFrom = $request->getParam('startdate', '');
        $dateTo = $request->getParam('enddate', '');
        $oprId = $this->getLoginId();
        $oprModel = new OprModel();
        list($pageNum, $rowFrom, $rowTo) = $oprModel->paginationParameters($pageNum, $pageLimit);
        //$totalCount = $oprModel->getWaitListCount($oprId, $dateFrom, $dateTo);

        if (empty($dateFrom)) {
            $dateFrom = '2019-01-01';
        }
        if (empty($dateTo)) {
            $dateTo = '2099-12-12';
        }

        $caseResumeApi = new CaseResumeApi();
        $timecontrol_begin = strtotime($dateFrom);
        $timecontrol_end = strtotime($dateTo) + 24 * 3600 - 1;
        $search_type = 1;
        $waitflow = 1;
        //$time1 = microtime(true);

        $resultTotal = $caseResumeApi->getWaitFlowTotalNum($oprId, $search_type, $waitflow, $timecontrol_begin, $timecontrol_end);
        //$time2 = microtime(true);
        $totalCount = isset($resultTotal['total']) ? $resultTotal['total'] : 0;

        if ($totalCount == 0) {
            $waitList = [];
        } else {
            //$time1 = microtime(true);
            $postData['tagadderid'] = $oprId;
            $postData['waitflow'] = 1;
            $postData['timecontrol_begin'] = $timecontrol_begin;
            $postData['timecontrol_end'] = $timecontrol_end;
            $caseResumeList = $caseResumeApi->getCaseResumeInfoByEs($postData, $rowFrom, $rowTo);
            //$time2 = microtime(true);
            $waitList = $oprModel->getWaitList($oprId, $caseResumeList);
        }

        return $this->json(['status' => true, 'message' => '获取成功', 'waitlist' => $waitList, 'totalcount' => $totalCount, 'pagenum' => $pageNum]);
    }

    /**
     * 发送手机验证码
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function sendPhoneAuthCode(Request $request) {
        $telPhone = $request->getParam('telphone');
        $verifyCode = $request->getParam('verifycode');
        $uuid = $request->getParam('uuid');

        //验证图形验证码
        $action = '_mpbind';
        $result = Captcha::check('image', ($uuid . $action), $verifyCode);
        if (!$result) {
            return $this->json(['status' => -1, 'message' => '验证码错误']);
        }

        $loginId = $this->getLoginId();
        $oprModel = new OprModel();
        $content = '欢迎使用无忧RPO系统，您正在修改绑定手机，验证码为##code##,有效期##expire##分钟,请勿泄露给他人';
        $result = $oprModel->sendMpVerifyCode($loginId, $telPhone, '_mpbind', $content);
        return $this->json($result);
    }

    /**
     * 绑定手机
     * @param Request $request
     * @return \EchoPHP\Http\Response\JsonResponse
     * @throws \Exception
     */
    public function bindPhone(Request $request) {
        $telPhone = $request->getParam('telphone');
        $verifyCode = $request->getParam('verifycode');
        $loginId = $this->getLoginId();

        $oprModel = new OprModel();
        $result = $oprModel->bindPhone($loginId, $telPhone, $verifyCode);
        return $this->json($result);
    }

}